import axios from '../index'

/**
 * 设备Tab API管理器
 */
class DeviceTabManager {
    constructor() {
        this.baseUrl = '/device'
    }

    // ========== 网络适配器相关 ==========
    async getNetworkAdapters() {
        console.log('🔍 [DeviceTabManager] 获取网络适配器列表')
        try {
            const response = await axios.get(`${this.baseUrl}/network-adapters`)
            console.log('✅ [DeviceTabManager] 获取网络适配器列表成功')
            return response
        } catch (error) {
            console.error('❌ [DeviceTabManager] 获取网络适配器列表失败:', error)
            throw error
        }
    }

    // ========== 设备搜索和连接 ==========
    async getGateWayDeviceList(params) {
        console.log('🔍 [DeviceTabManager] 获取网关设备列表')
        try {
            const response = await axios.get(`${this.baseUrl}/list`, {params})
            console.log('✅ [DeviceTabManager] 获取网关设备列表成功')
            return response
        } catch (error) {
            console.error('❌ [DeviceTabManager] 获取网关设备列表失败:', error)
            throw error
        }
    }

    async searchDevices(params = {}) {
        console.log('🔍 [DeviceTabManager] 搜索设备')
        try {
            const response = await axios.get(`${this.baseUrl}/search`, { params })
            console.log('✅ [DeviceTabManager] 搜索设备成功')
            return response
        } catch (error) {
            console.error('❌ [DeviceTabManager] 搜索设备失败:', error)
            throw error
        }
    }

    async connectDevice(deviceData) {
        console.log('🔌 [DeviceTabManager] 连接设备:', deviceData)
        try {
            const response = await axios.post(`${this.baseUrl}/connect`, deviceData)
            console.log('✅ [DeviceTabManager] 连接设备成功')
            return response
        } catch (error) {
            console.error('❌ [DeviceTabManager] 连接设备失败:', error)
            throw error
        }
    }

    async disconnectDevice(deviceData) {
        console.log('🔌 [DeviceTabManager] 断开设备连接:', deviceData)
        try {
            const response = await axios.post(`${this.baseUrl}/disconnect`, deviceData)
            console.log('✅ [DeviceTabManager] 断开设备连接成功')
            return response
        } catch (error) {
            console.error('❌ [DeviceTabManager] 断开设备连接失败:', error)
            throw error
        }
    }

    // 直接连接设备
    async directConnect(connectData) {
        console.log('🔌 [DeviceTabManager] 直接连接设备:', connectData)
        try {
            const response = await axios.post(`${this.baseUrl}/direct-connect`, connectData)
            console.log('✅ [DeviceTabManager] 直接连接设备成功')
            return response
        } catch (error) {
            console.error('❌ [DeviceTabManager] 直接连接设备失败:', error)
            throw error
        }
    }

    // Hub连接设备
    async hubConnect(connectData) {
        console.log('🔌 [DeviceTabManager] Hub连接设备:', connectData)
        try {
            const response = await axios.post(`${this.baseUrl}/hub-connect`, connectData)
            console.log('✅ [DeviceTabManager] Hub连接设备成功')
            return response
        } catch (error) {
            console.error('❌ [DeviceTabManager] Hub连接设备失败:', error)
            throw error
        }
    }

    // 自动搜索连接设备
    async autoConnect(connectData) {
        console.log('🔌 [DeviceTabManager] 自动搜索连接设备:', connectData)
        try {
            const response = await axios.post(`${this.baseUrl}/auto-connect`, connectData)
            console.log('✅ [DeviceTabManager] 自动搜索连接设备成功')
            return response
        } catch (error) {
            console.error('❌ [DeviceTabManager] 自动搜索连接设备失败:', error)
            throw error
        }
    }

    async refreshDeviceList() {
        console.log('🔄 [DeviceTabManager] 刷新设备列表')
        try {
            const response = await axios.post(`${this.baseUrl}/refresh`)
            console.log('✅ [DeviceTabManager] 刷新设备列表成功')
            return response
        } catch (error) {
            console.error('❌ [DeviceTabManager] 刷新设备列表失败:', error)
            throw error
        }
    }

    // ========== 串口相关功能 (新增) ==========
    /**
     * 获取串口列表
     * @returns {Promise<Array<string>>} 串口列表
     */
    async getSerialPortList() {
        console.log('🔍 [DeviceTabManager] 获取串口列表')
        try {
            const response = await axios.get(`${this.baseUrl}/serial-ports`)
            console.log('✅ [DeviceTabManager] 获取串口列表成功')
            return response
        } catch (error) {
            console.error('❌ [DeviceTabManager] 获取串口列表失败:', error)
            throw error
        }
    }

    /**
     * 测试网络连接
     * @param {Object} params 连接参数
     * @param {string} params.ip IP地址
     * @param {number} params.port 端口号
     * @returns {Promise<Object>} 测试结果
     */
    async testNetworkConnection(params) {
        console.log('🔍 [DeviceTabManager] 测试网络连接:', params)
        try {
            const response = await axios.post(`${this.baseUrl}/test-network`, params)
            console.log('✅ [DeviceTabManager] 测试网络连接成功')
            return response
        } catch (error) {
            console.error('❌ [DeviceTabManager] 测试网络连接失败:', error)
            throw error
        }
    }

    /**
     * 打开串口
     * @param {Object} params 串口参数
     * @param {string} params.port 串口名称
     * @param {number} params.baudRate 波特率
     * @returns {Promise<Object>} 操作结果
     */
    async openSerialPort(params) {
        console.log('🔌 [DeviceTabManager] 打开串口:', params)
        try {
            const response = await axios.post(`${this.baseUrl}/serial-port/open`, params)
            console.log('✅ [DeviceTabManager] 打开串口成功')
            return response
        } catch (error) {
            console.error('❌ [DeviceTabManager] 打开串口失败:', error)
            throw error
        }
    }

    /**
     * 关闭串口
     * @returns {Promise<Object>} 操作结果
     */
    async closeSerialPort() {
        console.log('🔌 [DeviceTabManager] 关闭串口')
        try {
            const response = await axios.post(`${this.baseUrl}/serial-port/close`)
            console.log('✅ [DeviceTabManager] 关闭串口成功')
            return response
        } catch (error) {
            console.error('❌ [DeviceTabManager] 关闭串口失败:', error)
            throw error
        }
    }

    /**
     * 通过串口下载配置
     * @returns {Promise<Object>} 操作结果
     */
    async downloadConfigViaSerial() {
        console.log('📥 [DeviceTabManager] 通过串口下载配置')
        try {
            const response = await axios.post(`${this.baseUrl}/config/download/serial`)
            console.log('✅ [DeviceTabManager] 通过串口下载配置成功')
            return response
        } catch (error) {
            console.error('❌ [DeviceTabManager] 通过串口下载配置失败:', error)
            throw error
        }
    }

    /**
     * 通过网络下载配置
     * @param {Object} params 连接参数
     * @param {string} params.ip IP地址
     * @param {number} params.port 端口号
     * @returns {Promise<Object>} 操作结果
     */
    async downloadConfigViaNetwork(params) {
        console.log('📥 [DeviceTabManager] 通过网络下载配置:', params)
        try {
            const response = await axios.post(`${this.baseUrl}/config/download/network`, params)
            console.log('✅ [DeviceTabManager] 通过网络下载配置成功')
            return response
        } catch (error) {
            console.error('❌ [DeviceTabManager] 通过网络下载配置失败:', error)
            throw error
        }
    }

    /**
     * 通过串口生成文件
     * @returns {Promise<Object>} 操作结果
     */
    async generateFileViaSerial() {
        console.log('📄 [DeviceTabManager] 通过串口生成文件')
        try {
            const response = await axios.post(`${this.baseUrl}/file/generate/serial`)
            console.log('✅ [DeviceTabManager] 通过串口生成文件成功')
            return response
        } catch (error) {
            console.error('❌ [DeviceTabManager] 通过串口生成文件失败:', error)
            throw error
        }
    }

    /**
     * 通过网络生成文件
     * @param {Object} params 连接参数
     * @param {string} params.ip IP地址
     * @param {number} params.port 端口号
     * @returns {Promise<Object>} 操作结果
     */
    async generateFileViaNetwork(params) {
        console.log('📄 [DeviceTabManager] 生成文件（网络模式）:', params)
        try {
            const response = await axios.post(`${this.baseUrl}/file/generate/network`, params)
            console.log('✅ [DeviceTabManager] 生成文件（网络模式）成功')
            return response
        } catch (error) {
            console.error('❌ [DeviceTabManager] 生成文件（网络模式）失败:', error)
            throw error
        }
    }

    /**
     * 停止下载
     * @returns {Promise<Object>} 操作结果
     */
    async stopDownload() {
        console.log('🛑 [DeviceTabManager] 停止下载')
        try {
            const response = await axios.post(`${this.baseUrl}/download/stop`)
            console.log('✅ [DeviceTabManager] 停止下载成功')
            return response
        } catch (error) {
            console.error('❌ [DeviceTabManager] 停止下载失败:', error)
            throw error
        }
    }

    /**
     * 获取下载进度
     * @returns {Promise<Object>} 下载进度信息
     */
    async getDownloadProgress() {
        console.log('📊 [DeviceTabManager] 获取下载进度')
        try {
            const response = await axios.get(`${this.baseUrl}/download/progress`)
            console.log('✅ [DeviceTabManager] 获取下载进度成功')
            return response
        } catch (error) {
            console.error('❌ [DeviceTabManager] 获取下载进度失败:', error)
            throw error
        }
    }

    /**
     * 获取当前下载文件信息
     * @returns {Promise<Object>} 当前下载文件信息
     */
    async getCurrentDownloadFile() {
        console.log('📄 [DeviceTabManager] 获取当前下载文件信息')
        try {
            const response = await axios.get(`${this.baseUrl}/download/current-file`)
            console.log('✅ [DeviceTabManager] 获取当前下载文件信息成功')
            return response
        } catch (error) {
            console.error('❌ [DeviceTabManager] 获取当前下载文件信息失败:', error)
            throw error
        }
    }

    /**
     * 重启网关
     * @param {Object} data 包含设备信息和网络参数的数据
     * @returns {Promise<Object>} 操作结果
     */
    async restartGateway(data) {
        console.log('🔄 [DeviceTabManager] 重启网关:', data)
        try {
            const response = await axios.post(`${this.baseUrl}/gateway/restart`, data)
            console.log('✅ [DeviceTabManager] 重启网关请求成功')
            return response
        } catch (error) {
            console.error('❌ [DeviceTabManager] 重启网关失败:', error)
            throw error
        }
    }

    /**
     * 获取网关重启状态
     * @param {Object} params 包含设备信息的参数
     * @returns {Promise<Object>} 重启状态信息
     */
    async getGatewayRestartStatus(params) {
        console.log('🔍 [DeviceTabManager] 获取网关重启状态')
        try {
            const response = await axios.get(`${this.baseUrl}/gateway/restart/status`, { params })
            console.log('✅ [DeviceTabManager] 获取网关重启状态成功')
            return response
        } catch (error) {
            console.error('❌ [DeviceTabManager] 获取网关重启状态失败:', error)
            throw error
        }
    }

    /**
     * 更新固件
     * @param {FormData} formData 包含文件和参数的表单数据
     * @returns {Promise<Object>} 操作结果
     */
    async updateFirmware(formData) {
        console.log('📱 [DeviceTabManager] 更新固件')
        try {
            const response = await axios.post(`${this.baseUrl}/firmware/update`, formData)
            console.log('✅ [DeviceTabManager] 更新固件请求成功')
            return response
        } catch (error) {
            console.error('❌ [DeviceTabManager] 更新固件失败:', error)
            throw error
        }
    }

    /**
     * 获取固件更新状态
     * @param {Object} params 包含设备信息的参数
     * @returns {Promise<Object>} 更新状态信息
     */
    async getFirmwareUpdateStatus(params) {
        console.log('🔍 [DeviceTabManager] 获取固件更新状态')
        try {
            const response = await axios.get(`${this.baseUrl}/firmware/status`, { params })
            console.log('✅ [DeviceTabManager] 获取固件更新状态成功')
            return response
        } catch (error) {
            console.error('❌ [DeviceTabManager] 获取固件更新状态失败:', error)
            throw error
        }
    }

    /**
     * 更新到服务器
     * @param {Object} data 包含设备信息和网络参数的数据
     * @returns {Promise<Object>} 操作结果
     */
    async updateToServer(data) {
        console.log('☁️ [DeviceTabManager] 更新到服务器:', data)
        try {
            const response = await axios.post(`${this.baseUrl}/server/update`, data)
            console.log('✅ [DeviceTabManager] 更新到服务器请求成功')
            return response
        } catch (error) {
            console.error('❌ [DeviceTabManager] 更新到服务器失败:', error)
            throw error
        }
    }

    /**
     * 获取服务器更新状态
     * @param {Object} params 包含设备信息的参数
     * @returns {Promise<Object>} 更新状态信息
     */
    async getServerUpdateStatus(params) {
        console.log('🔍 [DeviceTabManager] 获取服务器更新状态')
        try {
            const response = await axios.get(`${this.baseUrl}/server/status`, { params })
            console.log('✅ [DeviceTabManager] 获取服务器更新状态成功')
            return response
        } catch (error) {
            console.error('❌ [DeviceTabManager] 获取服务器更新状态失败:', error)
            throw error
        }
    }

    /**
     * 更新到设备
     * @param {Object} data 包含设备信息和网络参数的数据
     * @returns {Promise<Object>} 操作结果
     */
    async updateToDevice(data) {
        console.log('📱 [DeviceTabManager] 更新到设备:', data)
        try {
            const response = await axios.post(`${this.baseUrl}/device/update`, data)
            console.log('✅ [DeviceTabManager] 更新到设备请求成功')
            return response
        } catch (error) {
            console.error('❌ [DeviceTabManager] 更新到设备失败:', error)
            throw error
        }
    }

    /**
     * 获取设备更新状态
     * @param {Object} params 包含设备信息的参数
     * @returns {Promise<Object>} 更新状态信息
     */
    async getDeviceUpdateStatus(params) {
        console.log('📊 [DeviceTabManager] 获取设备更新状态')
        try {
            const response = await axios.get(`${this.baseUrl}/device/update/status`, { params: JSON.parse(params) })
            console.log('✅ [DeviceTabManager] 获取设备更新状态成功')
            return response
        } catch (error) {
            console.error('❌ [DeviceTabManager] 获取设备更新状态失败:', error)
            throw error
        }
    }
}

export default DeviceTabManager 